"""
AI Prompts Management
AI提示词管理系统
"""
from typing import Dict, List, Optional, Any
from enum import Enum
from dataclasses import dataclass
import json

class PromptType(Enum):
    """提示词类型枚举"""
    QUESTION_GENERATION = "question_generation"
    GRADING = "grading"
    ANALYTICS = "analytics"
    CHEATING_DETECTION = "cheating_detection"
    ADAPTIVE_LEARNING = "adaptive_learning"
    CONTENT_MODERATION = "content_moderation"
    FEEDBACK_GENERATION = "feedback_generation"
    STUDY_RECOMMENDATION = "study_recommendation"

class DifficultyLevel(Enum):
    """难度级别枚举"""
    EASY = "easy"
    MEDIUM = "medium"
    HARD = "hard"
    ADVANCED = "advanced"

class Subject(Enum):
    """学科枚举"""
    MATH = "math"
    CHINESE = "chinese"
    ENGLISH = "english"
    SCIENCE = "science"
    PHYSICS = "physics"
    CHEMISTRY = "chemistry"
    BIOLOGY = "biology"
    HISTORY = "history"
    GEOGRAPHY = "geography"
    POLITICS = "politics"

@dataclass
class PromptTemplate:
    """提示词模板类"""
    id: str
    name: str
    description: str
    type: PromptType
    subject: Optional[Subject]
    difficulty: Optional[DifficultyLevel]
    template: str
    variables: List[str]
    examples: List[Dict[str, Any]]
    version: str = "1.0"
    is_active: bool = True
    metadata: Optional[Dict[str, Any]] = None

class PromptManager:
    """提示词管理器"""

    def __init__(self):
        self.templates: Dict[str, PromptTemplate] = {}
        self._initialize_default_templates()

    def _initialize_default_templates(self):
        """初始化默认提示词模板"""

        # 题目生成提示词
        self.add_template(PromptTemplate(
            id="math_question_generation",
            name="数学题目生成",
            description="用于生成数学题目的通用模板",
            type=PromptType.QUESTION_GENERATION,
            subject=Subject.MATH,
            template=self._get_math_question_template(),
            variables=["topic", "difficulty", "question_type", "count", "grade_level"],
            examples=[{
                "topic": "一元二次方程",
                "difficulty": "medium",
                "question_type": "single_choice",
                "count": 5,
                "grade_level": "九年级"
            }],
            metadata={"category": "algebra", "estimated_time": 300}
        ))

        self.add_template(PromptTemplate(
            id="chinese_reading_comprehension",
            name="语文阅读理解生成",
            description="生成语文阅读理解题目的模板",
            type=PromptType.QUESTION_GENERATION,
            subject=Subject.CHINESE,
            template=self._get_chinese_reading_template(),
            variables=["text_type", "topic", "difficulty", "question_count", "grade_level"],
            examples=[{
                "text_type": "现代文阅读",
                "topic": "记叙文",
                "difficulty": "medium",
                "question_count": 5,
                "grade_level": "八年级"
            }]
        ))

        self.add_template(PromptTemplate(
            id="english_grammar_question",
            name="英语语法题目生成",
            description="生成英语语法题目的模板",
            type=PromptType.QUESTION_GENERATION,
            subject=Subject.ENGLISH,
            template=self._get_english_grammar_template(),
            variables=["grammar_point", "difficulty", "question_type", "count", "grade_level"],
            examples=[{
                "grammar_point": "现在完成时",
                "difficulty": "medium",
                "question_type": "multiple_choice",
                "count": 10,
                "grade_level": "高中一年级"
            }]
        ))

        # 评分提示词
        self.add_template(PromptTemplate(
            id="essay_grading_detailed",
            name="作文详细评分",
            description="对作文进行详细评分和反馈",
            type=PromptType.GRADING,
            subject=Subject.CHINESE,
            template=self._get_essay_grading_template(),
            variables=["essay_content", "essay_prompt", "grade_level", "rubric", "max_score"],
            examples=[{
                "essay_content": "学生作文内容...",
                "essay_prompt": "题目：我的家乡",
                "grade_level": "八年级",
                "rubric": "内容30分，结构30分，语言25分，创新15分",
                "max_score": 100
            }]
        ))

        self.add_template(PromptTemplate(
            id="math_problem_solving_grading",
            name="数学解题步骤评分",
            description="对数学解答题进行评分",
            type=PromptType.GRADING,
            subject=Subject.MATH,
            template=self._get_math_grading_template(),
            variables=["problem", "student_solution", "expected_steps", "max_score"],
            examples=[{
                "problem": "解方程：x² + 5x + 6 = 0",
                "student_solution": "学生解答...",
                "expected_steps": ["因式分解", "求根", "验证"],
                "max_score": 15
            }]
        ))

        # 学习分析提示词
        self.add_template(PromptTemplate(
            id="learning_progress_analysis",
            name="学习进度分析",
            description="分析学生的学习进度和表现",
            type=PromptType.ANALYTICS,
            template=self._get_learning_analysis_template(),
            variables=["student_data", "time_period", "subjects", "performance_metrics"],
            examples=[{
                "student_data": "历史成绩数据...",
                "time_period": "最近3个月",
                "subjects": ["数学", "语文", "英语"],
                "performance_metrics": ["accuracy", "speed", "improvement_rate"]
            }]
        ))

        self.add_template(PromptTemplate(
            id="personalized_study_plan",
            name="个性化学习计划",
            description="根据学生情况生成个性化学习计划",
            type=PromptType.STUDY_RECOMMENDATION,
            template=self._get_study_plan_template(),
            variables=["student_level", "weak_areas", "goals", "time_available", "learning_style"],
            examples=[{
                "student_level": "中等",
                "weak_areas": ["代数", "几何证明"],
                "goals": "期末考试达到85分",
                "time_available": "每天2小时",
                "learning_style": "视觉学习"
            }]
        ))

        # 作弊检测提示词
        self.add_template(PromptTemplate(
            id="answer_pattern_analysis",
            name="答题模式分析",
            description="分析学生的答题模式以检测可能的作弊行为",
            type=PromptType.CHEATING_DETECTION,
            template=self._get_cheating_detection_template(),
            variables=["answer_patterns", "time_stamps", "student_history", "class_average"],
            examples=[{
                "answer_patterns": "答题数据...",
                "time_stamps": "时间戳数据...",
                "student_history": "历史表现...",
                "class_average": "班级平均..."
            }]
        ))

    def add_template(self, template: PromptTemplate) -> None:
        """添加提示词模板"""
        self.templates[template.id] = template

    def get_template(self, template_id: str) -> Optional[PromptTemplate]:
        """获取提示词模板"""
        return self.templates.get(template_id)

    def get_templates_by_type(self, prompt_type: PromptType) -> List[PromptTemplate]:
        """根据类型获取提示词模板"""
        return [t for t in self.templates.values() if t.type == prompt_type and t.is_active]

    def get_templates_by_subject(self, subject: Subject) -> List[PromptTemplate]:
        """根据学科获取提示词模板"""
        return [t for t in self.templates.values() if t.subject == subject and t.is_active]

    def render_template(self, template_id: str, variables: Dict[str, Any]) -> str:
        """渲染提示词模板"""
        template = self.get_template(template_id)
        if not template:
            raise ValueError(f"Template {template_id} not found")

        # 验证必需变量
        missing_vars = [var for var in template.variables if var not in variables]
        if missing_vars:
            raise ValueError(f"Missing required variables: {missing_vars}")

        # 渲染模板
        rendered = template.template
        for var, value in variables.items():
            rendered = rendered.replace(f"{{{var}}}", str(value))

        return rendered

    def list_templates(self) -> List[Dict[str, Any]]:
        """列出所有模板"""
        return [
            {
                "id": t.id,
                "name": t.name,
                "description": t.description,
                "type": t.type.value,
                "subject": t.subject.value if t.subject else None,
                "difficulty": t.difficulty.value if t.difficulty else None,
                "version": t.version,
                "is_active": t.is_active
            }
            for t in self.templates.values()
        ]

    # 具体的提示词模板定义
    def _get_math_question_template(self) -> str:
        return """
你是一个专业的数学题目生成助手。请根据以下要求生成高质量的数学题目：

知识点：{topic}
难度级别：{difficulty}
题目类型：{question_type}
题目数量：{count}
目标年级：{grade_level}

生成要求：
1. 题目应符合对应年级的教学大纲要求
2. 难度设置要准确匹配目标水平
3. 题目描述要清晰、准确、无歧义
4. 提供完整的解题步骤和答案
5. 包含详细的解析和知识点说明

请按照以下JSON格式返回：
{{
    "questions": [
        {{
            "title": "题目标题",
            "content": "题目内容",
            "options": ["选项A", "选项B", "选项C", "选项D"],
            "correct_answer": "正确答案",
            "explanation": "详细解析",
            "solution_steps": ["解题步骤1", "解题步骤2", "解题步骤3"],
            "key_points": ["知识点1", "知识点2"],
            "difficulty": "{difficulty}",
            "estimated_time": 300,
            "score": 10
        }}
    ]
}}
"""

    def _get_chinese_reading_template(self) -> str:
        return """
你是一个专业的语文题目生成助手。请生成高质量的语文阅读理解题目：

文本类型：{text_type}
主题：{topic}
难度级别：{difficulty}
题目数量：{question_count}
目标年级：{grade_level}

生成要求：
1. 首先生成一篇符合要求的阅读材料（约300-800字）
2. 基于阅读材料设计多种类型的题目
3. 题目类型应包括：内容理解、细节把握、主旨归纳、写作手法等
4. 提供详细的答案解析和评分标准

请按照以下JSON格式返回：
{{
    "reading_material": {{
        "title": "文章标题",
        "content": "文章内容",
        "type": "{text_type}",
        "word_count": 字数,
        "grade_level": "{grade_level}"
    }},
    "questions": [
        {{
            "type": "选择题/简答题/判断题",
            "content": "题目内容",
            "options": ["选项A", "选项B", "选项C", "选项D"],
            "correct_answer": "正确答案",
            "explanation": "详细解析",
            "score": 分值,
            "difficulty": "{difficulty}"
        }}
    ]
}}
"""

    def _get_english_grammar_template(self) -> str:
        return """
You are a professional English grammar question generator. Please generate high-quality grammar questions based on the following requirements:

Grammar Point: {grammar_point}
Difficulty Level: {difficulty}
Question Type: {question_type}
Number of Questions: {count}
Target Grade: {grade_level}

Requirements:
1. Questions should accurately test the specified grammar point
2. Include clear contexts and scenarios
3. Provide comprehensive explanations for correct answers
4. Include common distractors for multiple choice questions
5. Cover different aspects of the grammar point

Please return in the following JSON format:
{{
    "questions": [
        {{
            "title": "Question Title",
            "content": "Question with context",
            "options": ["Option A", "Option B", "Option C", "Option D"],
            "correct_answer": "Correct Answer",
            "explanation": "Detailed explanation",
            "grammar_focus": "{grammar_point}",
            "difficulty": "{difficulty}",
            "estimated_time": 60,
            "score": 5
        }}
    ]
}}
"""

    def _get_essay_grading_template(self) -> str:
        return """
你是一个专业的作文评分助手。请根据以下标准对学生的作文进行详细评分和反馈：

作文题目：{essay_prompt}
学生年级：{grade_level}
评分标准：{rubric}
满分：{max_score}分

学生作文内容：
{essay_content}

评分维度：
1. 内容主题（30分）：主题明确性、内容充实性、立意深度
2. 结构组织（25分）：结构完整性、层次清晰度、过渡自然性
3. 语言表达（25分）：语言准确性、词汇丰富性、句式变化
4. 思想创新（20分）：观点独特性、思维深度、创意表现

请按照以下格式提供详细反馈：
{{
    "total_score": 总分,
    "score_breakdown": {{
        "content_theme": 得分,
        "structure_organization": 得分,
        "language_expression": 得分,
        "thought_innovation": 得分
    }},
    "strengths": [
        "优点1",
        "优点2",
        "优点3"
    ],
    "areas_for_improvement": [
        "需要改进的方面1",
        "需要改进的方面2"
    ],
    "detailed_feedback": "详细的整体评语",
    "specific_suggestions": [
        "具体改进建议1",
        "具体改进建议2"
    ],
    "grade_level_assessment": "相对于年级水平的评价"
}}
"""

    def _get_math_grading_template(self) -> str:
        return """
你是一个专业的数学解题评分助手。请对学生的数学解答进行评分：

题目：{problem}
学生解答：{student_solution}
预期解题步骤：{expected_steps}
满分：{max_score}分

评分标准：
1. 解题思路（30%）：方法选择是否恰当，思路是否清晰
2. 步骤完整性（30%）：解题步骤是否完整，逻辑是否严密
3. 结果正确性（25%）：最终答案是否正确
4. 表达规范性（15%）：数学符号使用是否规范，书写是否清晰

请提供详细的评分和反馈：
{{
    "total_score": 得分,
    "score_breakdown": {{
        "method_approach": 得分,
        "step_completeness": 得分,
        "result_correctness": 得分,
        "expression_standardization": 得分
    }},
    "step_analysis": [
        {{
            "step": "步骤描述",
            "score": 步骤得分,
            "feedback": "步骤反馈"
        }}
    ],
    "error_analysis": {{
        "errors": ["错误1", "错误2"],
        "error_types": ["概念错误", "计算错误"],
        "corrections": ["纠正方法1", "纠正方法2"]
    }},
    "detailed_feedback": "详细的评语和建议",
    "improvement_suggestions": ["改进建议1", "改进建议2"]
}}
"""

    def _get_learning_analysis_template(self) -> str:
        return """
你是一个专业的学习分析助手。请分析学生的学习数据并提供深度洞察：

分析时间段：{time_period}
涉及学科：{subjects}
分析指标：{performance_metrics}

学生数据：
{student_data}

请提供全面的分析报告：
{{
    "overall_performance": {{
        "trend": "上升趋势/下降趋势/稳定",
        "average_score": 平均分数,
        "improvement_rate": 提升幅度,
        "rank_in_class": "班级排名情况"
    }},
    "subject_analysis": {{
        "strengths": ["优势学科1", "优势学科2"],
        "weak_areas": ["薄弱学科1", "薄弱学科2"],
        "improvement_suggestions": {{
            "学科名": "具体改进建议"
        }}
    }},
    "learning_patterns": {{
        "strengths": ["学习优势1", "学习优势2"],
        "challenges": ["学习挑战1", "学习挑战2"],
        "recommendations": ["学习建议1", "学习建议2"]
    }},
    "detailed_insights": "详细的学习分析洞察",
    "actionable_recommendations": [
        "可执行建议1",
        "可执行建议2"
    ]
}}
"""

    def _get_study_plan_template(self) -> str:
        return """
你是一个专业的学习规划顾问。请根据学生情况制定个性化的学习计划：

学生水平：{student_level}
薄弱领域：{weak_areas}
学习目标：{goals}
可用时间：{time_available}
学习风格：{learning_style}

请制定详细的学习计划：
{{
    "study_plan_summary": "学习计划概述",
    "weekly_schedule": [
        {{
            "day": "星期一",
            "subjects": ["科目1", "科目2"],
            "time_allocation": "时间分配",
            "specific_tasks": ["具体任务1", "具体任务2"],
            "goals": ["当日目标1", "当日目标2"]
        }}
    ],
    "subject_focus": {{
        "薄弱学科": {{
            "priority": "优先级",
            "daily_time": "每日时间",
            "key_topics": ["重点主题1", "重点主题2"],
            "study_methods": ["学习方法1", "学习方法2"],
            "practice_frequency": "练习频率"
        }}
    }},
    "learning_resources": {{
        "books": ["推荐书籍1", "推荐书籍2"],
        "online_resources": ["在线资源1", "在线资源2"],
        "practice_materials": ["练习材料1", "练习材料2"]
    }},
    "milestone_goals": [
        {{
            "milestone": "里程碑目标",
            "target_date": "目标日期",
            "success_criteria": "成功标准"
        }}
    ],
    "monitoring_strategy": "学习进度监控方法",
    "adjustment_mechanism": "计划调整机制"
}}
"""

    def _get_cheating_detection_template(self) -> str:
        return """
你是一个专业的学习行为分析助手。请分析学生的答题数据，识别可能的异常模式：

答题模式数据：{answer_patterns}
答题时间戳：{time_stamps}
学生历史表现：{student_history}
班级平均水平：{class_average}

请进行全面的异常检测分析：
{{
    "risk_assessment": {{
        "overall_risk_level": "低/中/高风险",
        "risk_score": 风险评分(0-100),
        "confidence_level": "置信度百分比"
    }},
    "suspicious_patterns": [
        {{
            "pattern_type": "异常模式类型",
            "description": "具体描述",
            "risk_level": "风险等级",
            "evidence": "证据说明"
        }}
    ],
    "behavioral_analysis": {{
        "time_pattern_anomalies": "时间模式异常分析",
        "answer_consistency": "答案一致性分析",
        "difficulty_mismatch": "难度不匹配分析",
        "performance_variance": "表现波动分析"
    }},
    "statistical_indicators": {{
        "z_score": "统计学Z分数",
        "standard_deviations": "标准差倍数",
        "correlation_coefficient": "相关系数"
    }},
    "recommendations": [
        "建议措施1",
        "建议措施2"
    ],
    "requires_human_review": true/false
}}
"""

# 创建全局提示词管理器实例
prompt_manager = PromptManager()

# 导出常用函数
def get_prompt_template(template_id: str) -> Optional[PromptTemplate]:
    """获取提示词模板"""
    return prompt_manager.get_template(template_id)

def render_prompt(template_id: str, variables: Dict[str, Any]) -> str:
    """渲染提示词"""
    return prompt_manager.render_template(template_id, variables)

def list_available_templates() -> List[Dict[str, Any]]:
    """列出可用的提示词模板"""
    return prompt_manager.list_templates()